<template>
  <div>
    <element-table class="mt-20"
                   v-loading="loading"
                   :columns="columns"
                   :data="hospitalList"
                   pager
                   :pageTotal="pageTotal"
                   :pageSize="pageSize"
                   :pageIndex="pageIndex"
                   height="300">

      <template v-slot:doctorDtos="{row}">
        <template v-if="row.doctorDtos && row.doctorDtos.length > 0">
          <el-tag type="success"
                  v-for="item in row.doctorDtos"
                  :key="item.id"
                  style="margin-right:5px;">
            {{item.nickName}}
          </el-tag>
        </template>
        <span v-else>无</span>
      </template>
      <template v-slot:option="{row}">
        <el-button type="primary"
                   @click="handleOption('edit', row)">编 辑</el-button>
        <el-button type="danger"
                   @click="handleOption('add', row)">新 增</el-button>
      </template>
    </element-table>
    <el-dialog title="操作"
               :visible.sync="dialogVisible"
               append-to-body
               width="40%"
               @close="dialogVisible = false">
      <el-form ref="searchParamsRef"
               :model="searchParams"
               label-width="120px">
        <el-form-item label="复核医生：">
          <el-select v-model="searchParams.reCheckDoctorIds"
                     placeholder="请选择复核医生"
                     multiple
                     filterable
                     remote
                     reserve-keyword
                     :remote-method="remoteMethod"
                     @change="handleSelect">
            <el-option v-for="item in options4"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
          <el-button type="primary"
                     @click="handleAdd(searchParams.reCheckDoctorIds)">增 加</el-button>
        </el-form-item>
        <el-form-item label="已选医生：">
          <el-table :data="dataList"
                    border
                    style="width: 100%">
            <el-table-column prop="nickName"
                             label="姓名"
                             align="center">
            </el-table-column>
            <el-table-column prop="departmentName"
                             label="科室"
                             align="center">
            </el-table-column>
            <el-table-column prop="doctorTitleName"
                             label="职称"
                             align="center">
            </el-table-column>
            <el-table-column prop="op"
                             label="操作"
                             align="center">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="delRow(dataList, scope.$index)">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import elementTable from '@/base/ElementTable';
  export default {
    props: {
      hospitalList: {
        type: Array
      },
      visible: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        loading: false,
        dialogVisible: false,
        columns: [
          {
            label: '医院名称',
            prop: 'hospitalName'
          },
          {
            label: '是否有医联体单位',
            prop: 'medicalUnionId',
            formatter: (row, cellValue) => {
              return row.medicalUnionId === 0 ? '没有' : '有'
            },
          },
          {
            label: '复核医生',
            prop: 'doctorDtos',
            isSlot: true
          },
          {
            label: '操作',
            prop: 'option',
            width: 200,
            isSlot: true
          }
        ],
        pageTotal: 0,
        pageIndex: 1,
        pageSize: 10,
        rowData: {},
        searchParams: {
          reCheckDoctorIds: []
        },
        options4: [],
        dataList: [],
        lists: []
      }
    },
    methods: {

      getList () {
        setTimeout(() => {
          this.pageTotal = this.hospitalList.length;
        }, 3000)
      },
      handleOption (op, row) {
        this.dialogVisible = true;
        switch (op) {
          case 'add':
            this.rowData = Object.assign({}, row);
            this.dataList = [];
            this.searchParams.reCheckDoctorIds = [];
            break;
          case 'edit':
            this.rowData = Object.assign({}, row);
            this.searchParams.reCheckDoctorIds = [];
            this.dataList = this.rowData.doctorDtos;
            break;
        }
      },
      delRow (table, index) {
        table.splice(index, 1);
      },
      // 远程搜索医生
      remoteMethod (query) {
        if (query !== '') {
          let _this = this;
          _this.loading = true;
          this.post(this.api.medicalConsortium.getReCheckDoctorList, {
            hospitalId: this.rowData.hospitalId,
            nickName: query
          }).then(({ data: res }) => {
            if (res.code === '200') {
              _this.loading = false;
              _this.lists = res.object;
            }
          })

          setTimeout(() => {
            _this.loading = false;
            let resList = _this.lists.map(item => ({
              ...item,
              label: item.nickName, value: item.id
            }))
            _this.options4 = resList.filter(item => item.label.indexOf(query) > -1);

          }, 200)
        } else {
          _this.options4 = [];
        }
      },
      handleSelect (item) {
        this.searchParams.reCheckDoctorIds = item;
      },
      handleAdd (params) {
        let temp = this.lists.filter(item => params.some(ele => ele === item.id));
        let newArray = []
        temp.forEach(list => {
          if ((list.doctorTitleType == 0 || list.doctorTitleType === 2 || list.doctorTitleType === 7) && list.doctorTitleLevel <= 3) {
            newArray.push({
              ...list,
              value: list.id,
              label: list.nickName
            })

          } else {
            this.$message.warning('职级不符合!');
            this.searchParams.reCheckDoctorIds = [];
          }
        });
        this.dataList = this.removeDuplicatedItem2([...this.dataList, ...newArray], 'id');
        this.dataList.forEach(item => newArray.some(ele => {
          if (ele.id === item.id) {
            this.$message.warning('重复添加!');
            this.searchParams.reCheckDoctorIds = [];
          }
        }))

      },
      onSubmit () {
        let temp = this.dataList.map(item => item.id);
        this.hospitalList.forEach(item => {
          if (item.hospitalId === this.rowData.hospitalId) {
            item.doctorDtos = this.$set(item, 'doctorDtos', this.dataList);
            item.reCheckDoctorIds = this.$set(item, 'reCheckDoctorIds', JSON.stringify(temp));
          }
        });
        this.dialogVisible = false;
      },
      removeDuplicatedItem2 (arr, key) {
        var result = [];
        var obj = {};
        for (var i = 0; i < arr.length; i++) {
          if (!obj[arr[i][key]]) {
            result.push(arr[i]);
            obj[arr[i][key]] = true;
          }
        }
        return result;
      }
    },
    created () {
      this.getList();
    },
    components: {
      'element-table': elementTable
    }
  }
</script>
<style lang="scss" scoped>
  .common-table {
    padding-bottom: 0;
  }
  .doctor-list {
    display: flex;
    .doctor-li {
      padding-bottom: 10px;
    }
  }
</style>